package org.zhangyp.n01jdkapi.n04thread;

/**
 * todo
 *
 * @author ypzhang
 * @since 2025/8/8
 */
public class ThreadTest {

    public synchronized void test0() {
        String name = Thread.currentThread().getName();
        System.out.println(name+" start");
        // 打印当前线程的名称和线程ID
        System.out.println("当前线程名称：" + name + "，线程ID：" + Thread.currentThread().getId());

        try {
            System.out.println(name + " 执行中。。。。。");
            this.wait();
            System.out.println(name + " 继续执行。。。。。");
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name+" end");
    }

//    public synchronized void test1() {
//        System.out.println("test1 start");
//        // 打印当前线程的名称和线程ID
//        System.out.println("当前线程名称：" + Thread.currentThread().getName() + "，线程ID：" + Thread.currentThread().getId());
//        try {
//            System.out.println("test1 执行中。。。。。");
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println("test1 end");
//        //this.notifyAll();
//    }

    public static void main(String[] args) throws InterruptedException {
  /*      ThreadTest test = new ThreadTest();
//        for(int i = 0; i < 100; i++){
//            Thread t1 = new Thread(test::test0, "Thread-" + i);
//            t1.start();
//        }

        Thread t1 = new Thread(test::test0, "子线程");
        t1.start();
        Thread.sleep(10);
        // 正确的方式：在同步代码块中调用 notify()
        synchronized (test) {
            Thread.sleep(1000);
            test.notify();
        }*/

        Chopstick c1 = new Chopstick("1号筷子");
        Chopstick c2 = new Chopstick("2号筷子");
        Chopstick c3 = new Chopstick("3号筷子");
        Chopstick c4 = new Chopstick("4号筷子");
        Chopstick c5 = new Chopstick("5号筷子");

        Philosopher p1 = new Philosopher("哲学家1", c1, c2);
        Philosopher p2 = new Philosopher("哲学家2", c2, c3);
        Philosopher p3 = new Philosopher("哲学家3", c3, c4);
        Philosopher p4 = new Philosopher("哲学家4", c4, c5);
        Philosopher p5 = new Philosopher("哲学家5", c5, c1);

        Thread thread1 = new Thread(p1);
        Thread thread2 = new Thread(p2);
        Thread thread3 = new Thread(p3);
        Thread thread4 = new Thread(p4);
        Thread thread5 = new Thread(p5);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }
}
